import {
  projects,
  crossingPoints,
  constructionSchemes,
  constructionMethodTemplates,
  documentTemplates,
  systemVariableConfigs,
} from "../mock/Index";

// 模拟异步请求
const delay = (data, timeout = 500) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(data), timeout);
  });
};

export const Project = {
  list: (sort = "") =>
    delay(
      [...projects].sort((a, b) => {
        if (sort === "-created_date")
          return new Date(b.created_date) - new Date(a.created_date);
        return new Date(a.created_date) - new Date(b.created_date);
      })
    ),
  get: (id) => delay(projects.find((p) => p.id === id) || null),
};

export const CrossingPoint = {
  list: (sort = "") =>
    delay(
      [...crossingPoints].sort((a, b) => {
        if (sort === "-created_date")
          return new Date(b.created_date) - new Date(a.created_date);
        return new Date(a.created_date) - new Date(b.created_date);
      })
    ),
  filter: (conditions) => {
    let result = [...crossingPoints];
    if (conditions.projectId) {
      result = result.filter((p) => p.projectId === conditions.projectId);
    }
    return delay(result);
  },
};

export const ConstructionScheme = {
  list: (sort = "") =>
    delay(
      [...constructionSchemes].sort((a, b) => {
        if (sort === "-updated_date")
          return new Date(b.updated_date) - new Date(a.updated_date);
        return new Date(a.updated_date) - new Date(b.updated_date);
      })
    ),
  filter: (conditions) => {
    let result = [...constructionSchemes];
    if (conditions.crossingPointId?.$in) {
      result = result.filter((s) =>
        conditions.crossingPointId.$in.includes(s.crossingPointId)
      );
    }
    return delay(result);
  },
};

export const ConstructionMethodTemplate = {
  list: () => delay([...constructionMethodTemplates]),
};

export const DocumentTemplate = {
  list: (sort = "") =>
    delay(
      [...documentTemplates].sort((a, b) => {
        if (sort === "-updated_date")
          return new Date(b.updated_date) - new Date(a.updated_date);
        return new Date(a.updated_date) - new Date(b.updated_date);
      })
    ),
};

export const SystemVariableConfig = {
  list: () => delay([...systemVariableConfigs]),
};

// 保留其他实体的空实现，避免报错
export const Department = { list: () => delay([]) };
export const SchemeApproval = { list: () => delay([]) };
export const KnowledgeAudit = { list: () => delay([]) };
export const Standard = { list: () => delay([]) };
export const OperationalUnit = { list: () => delay([]) };
export const GlobalEvent = { list: () => delay([]) };
export const SystemConfig = { list: () => delay([]) };
export const SafetyRiskPoint = { list: () => delay([]) };
export const EmergencyMeasureTemplate = { list: () => delay([]) };
export const QualityIssueTemplate = { list: () => delay([]) };

// auth sdk:
export const User = {
  current: () => delay({ full_name: "系统管理员" }),
};
